package com.yubest.customserializer.anno;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Base64;

/**
 * @Author hweiyu
 * @Description
 * @Date 2021/9/29 11:51
 */
@Slf4j
public class Base64JsonSerializer extends JsonSerializer<byte[]> {

    @Override
    public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (null != value && value.length > 0) {
            gen.writeString(Base64.getEncoder().encodeToString(value));

            /**
             * 添加额外字段
             */
            // 获取序列化字段名称
            String fieldName = gen.getOutputContext().getCurrentName();
            gen.writeFieldName(fieldName + "Size");
            gen.writeNumber(value.length);
        }
    }
}
